package com.qcby.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.qcby.dao.UserDao;
import com.qcby.entity.User;
import com.qcby.entity.vo.UserVo;
import com.qcby.service.UserService;
import com.qcby.util.ResultObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author haozeWang
 * @create 2021-08-20 15:24
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /*登陆验证*/
    @Override
    public ResultObject login(UserVo user, HttpServletRequest request, HttpServletResponse response) {
       String code=user.getCode();//拿到验证码
        String session_code=request.getSession().getAttribute("code").toString();//拿到存储在服务器的校验验证码
        String msg="";
        Integer status_code=0;
        if(code.equals(session_code)){//验证码正确
            List<User> login = userDao.login(user);
            if(login.size()>0){
                msg="登陆成功";
                status_code=1;
                request.getSession().setAttribute("username",login.get(0).getUsername());
            }else{
                msg="登陆失败";
                status_code=0;
            }
           
        }else {
            msg="验证码错误";
            status_code=-1;
        }
        /*将旧验证码失效*/
        request.getSession().setAttribute("code", "");

        ResultObject resultObject = new ResultObject(status_code,msg);
        return resultObject;
    }
    /*获取验证码并回写*/

    @Override
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
            /*生成验证码*/
        ICaptcha captcha= CaptchaUtil.createLineCaptcha(116, 36,4,20);
        /*把码值存放在session*/
        request.getSession().setAttribute("code",captcha.getCode() );
        /*图片回写到前端*/
        captcha.write(response.getOutputStream());
    }
}
